package com.group.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    DefaultWebSessionManager defaultSessionManager;

    //从下往上配
    @Bean
    //ShrioFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);

        /*添加shiro内置过滤器
        anon : 无需认证即可访问
        authc : 必须认证才能访问
        user : 必须有 记住我 功能才能访问
        perms : 拥有对某个资源的权限才能访问
        role : 拥有某个角色权限才能访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/userInformation", "authc");
        //发送申请入队
        filterMap.put("/lookingprojects", "authc");
        filterMap.put("/pi/**", "authc");
        filterMap.put("/g/**", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登陆请求
        bean.setLoginUrl("/toLogin");
        String loginUrl = bean.getLoginUrl();
        System.out.println(loginUrl);
//        bean.setSuccessUrl("redirect:/myproject");
        //未授权
//        bean.setUnauthorizedUrl("/unAuthorized");
        return bean;
    }
    @Bean(name = "securityManager")
    //DefaultWebSecurityManager
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(defaultSessionManager);

        //关联Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean
    public DefaultWebSessionManager mySessionManager(){
        DefaultWebSessionManager defaultSessionManager = new DefaultWebSessionManager();
        //将sessionIdUrlRewritingEnabled属性设置成false
        defaultSessionManager.setSessionIdUrlRewritingEnabled(false);
        return defaultSessionManager;
    }


    //创建Realm对象，需要自定义UserRealm对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合shiroDialect：用来整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }

}
